<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2018 http://www.donglixia.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: 十万马 <962863675@qq.com>
// +----------------------------------------------------------------------
// | DateTime: 2018-02-09 16:17
// +----------------------------------------------------------------------

namespace app\common\behavior;

use think\Db;
use think\Request;

class LogVisit
{
    /**
     * 保存访问日志
     */
    public function run()
    {
        try {
            $request = Request::instance();
            $data = [];
            $data['user_id'] = !empty(user_info('user_id')) ? user_info('user_id') : 0;
            $data['url'] = $request->url(true);
            $data['module'] = $request->module();
            $data['controller'] = $request->controller();
            $data['action'] = $request->action();
            $data['params'] = json_encode($request->param());
            $data['ip'] = !empty($request->ip(1)) ? $request->ip(1) : 0;
            $data['number'] = 1;
            $data['type'] = !$request->isMobile() ? 1 : (is_weixin() ? 2 : 3);//类型：1 PC端，2 微信端，3 H5页面
            $data['create_time'] = time();

            $map = [];
            $map['ip'] = $data['ip'];
            $map['url'] = $data['url'];
            $map['create_time'] = ['>', strtotime(date('Y-m-d 00:00:00'))];
            $id = Db::name('log_visit')->where($map)->value('id');
            if (!empty($id)) {
                Db::name('log_visit')->where('id', $id)->update(['number'=>Db::raw('number+1')]);
            } else {
                Db::name('log_visit')->insert($data);
            }

            if ($data['controller'] == 'Goods') {
                add_read_num('goods');//记录产品阅读次数
            } elseif (in_array($data['controller'], ['News','Activity','Brand','College','Fund','About'])) {
                add_read_num('article');//记录文章阅读次数
            }
        } catch (\Exception $e) {
            save_error_log($e->getMessage().' ['.$e->getFile().':'.$e->getLine().']');
        }
    }

}

